package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Category;
import model.Myuser;
import model.Target;

import ejb.CategoryFacadeEJBRemote;
import ejb.TargetFacadeEJBRemote;
import ejb.UserFacadeEJBRemote;

/**
 * Servlet implementation class Home
 */
@WebServlet("/Home")
public class Home extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@PersistenceContext
	EntityManager em;
	
       @EJB CategoryFacadeEJBRemote cf;
       @EJB TargetFacadeEJBRemote tf;
       @EJB UserFacadeEJBRemote uf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Home() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		//"search_result", result);
        //request.setAttribute("result_num"
		PrintWriter out = response.getWriter();
        HttpSession session=request.getSession();
        String username=(String)session.getAttribute("username");
        if(username==null){
            out.print("Please login first! redirecting to Login...");
            response.setHeader("Refresh","2;URL=login.jsp");
        }
        else{
        	 	session.setAttribute("authority", uf.findUserByName(username).getAuthority());        	
        		//get and send search information from Search
        		String result_num=(String)request.getAttribute("result_num");
        		ArrayList<Target>  result=(ArrayList<Target>)request.getAttribute("search_result");
        		String categ=(String)request.getParameter("categ");
        		try{
        		if(result_num!=null && !result.isEmpty()){
        			request.setAttribute("result_num", result_num);
        			request.setAttribute("search_result", result);
        		}
        		else if(categ!=null){
       			List<Target> target_cate=tf.getTargetByCategotyID(Integer.parseInt(categ));
       			request.setAttribute("target_cate", target_cate);
        			//request.setAttribute("test", categ);
        		}
        			
        		else{														//default way to display
        			List<Target> targets_rated = tf.getAllTargetsByRate();
        			request.setAttribute("default_display", targets_rated);
        		}
        		}
        		catch(Exception e){
        			e.printStackTrace();
        		}
        		//get and send category list 
	        	List<Category> cates=cf.getAllCate();
	        	String num=Integer.toString( cates.size());
	        	
	        	//ask comments number
				List<Myuser> userlist = new ArrayList<Myuser>();
				userlist = uf.getAllUser();
				int[] userCnum = new int[userlist.size()];
				Myuser temp = new Myuser();
				for(int i=0;i<userlist.size();i++){
					temp = userlist.get(i);
					Query query=em.createQuery("SELECT COUNT (c.myuser1) FROM Mycomment c where c.myuser1 =:u");
					query.setParameter("u", temp);
					userCnum[i] = ((Number)query.getSingleResult()).intValue();
				}
				
				request.setAttribute("countlist", userCnum);
	        	request.setAttribute("num", num);
	        	request.setAttribute("cates", cates);
	        	request.setAttribute("ulist", userlist);
	        	
	        	//get and send book list
	        	
	        	request.getRequestDispatcher("home.jsp").forward(request, response);
	        	
        	
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
